package cn.wongshu.student.filter;

import cn.wongshu.student.pojo.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        //获取登入的请求头
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
            || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
            //如果是json方式登入的话
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authenticationToken = null;

            try(InputStream is = request.getInputStream()) {
                //将登入数据转化为实体类
                User user = mapper.readValue(is, User.class);
                authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
            } catch (IOException e) {
                e.printStackTrace();
                authenticationToken = new UsernamePasswordAuthenticationToken("","");
            }finally {
                setDetails(request,authenticationToken);
                return this.getAuthenticationManager().authenticate(authenticationToken);
            }


        }else {
            return super.attemptAuthentication(request,response);
        }


    }
}
